<template>
  <div class="network-statistics">
    <!-- 基础统计卡片 -->
    <a-row :gutter="[16, 16]" class="stats-cards">
      <a-col :xs="24" :sm="12" :md="6">
        <a-card size="small">
          <a-statistic
            title="节点总数"
            :value="statistics.totalNodes"
            :value-style="{ color: '#1890ff' }"
          >
            <template #prefix>
              <apartment-outlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12" :md="6">
        <a-card size="small">
          <a-statistic
            title="连接总数"
            :value="statistics.totalEdges"
            :value-style="{ color: '#52c41a' }"
          >
            <template #prefix>
              <share-alt-outlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12" :md="6">
        <a-card size="small">
          <a-statistic
            title="平均度数"
            :value="statistics.averageDegree"
            :precision="2"
            :value-style="{ color: '#722ed1' }"
          >
            <template #prefix>
              <node-index-outlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :xs="24" :sm="12" :md="6">
        <a-card size="small">
          <a-statistic
            title="网络密度"
            :value="statistics.networkDensity * 100"
            suffix="%"
            :precision="2"
            :value-style="{ color: '#fa8c16' }"
          >
            <template #prefix>
              <cluster-outlined />
            </template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 详细统计图表 -->
    <a-row :gutter="[16, 16]" class="stats-charts">
      <!-- 度数分布图 -->
      <a-col :xs="24" :lg="12">
        <a-card title="度数分布" size="small">
          <div ref="degreeDistributionRef" class="chart-container"></div>
        </a-card>
      </a-col>

      <!-- 节点类型分布图 -->
      <a-col :xs="24" :lg="12">
        <a-card title="节点类型分布" size="small">
          <div ref="nodeTypeDistributionRef" class="chart-container"></div>
        </a-card>
      </a-col>

      <!-- 关系类型分布图 -->
      <a-col :xs="24" :lg="12">
        <a-card title="关系类型分布" size="small">
          <div ref="relationshipTypeDistributionRef" class="chart-container"></div>
        </a-card>
      </a-col>

      <!-- 关系强度分布图 -->
      <a-col :xs="24" :lg="12">
        <a-card title="关系强度分布" size="small">
          <div ref="strengthDistributionRef" class="chart-container"></div>
        </a-card>
      </a-col>

      <!-- 中心性排名 -->
      <a-col :xs="24">
        <a-card title="中心性排名" size="small">
          <a-tabs v-model:activeKey="centralityTab" size="small">
            <a-tab-pane key="degree" tab="度中心性">
              <div ref="degreeCentralityRef" class="chart-container-large"></div>
            </a-tab-pane>
            <a-tab-pane key="betweenness" tab="介数中心性">
              <div ref="betweennessCentralityRef" class="chart-container-large"></div>
            </a-tab-pane>
            <a-tab-pane key="closeness" tab="接近中心性">
              <div ref="closenessCentralityRef" class="chart-container-large"></div>
            </a-tab-pane>
            <a-tab-pane key="eigenvector" tab="特征向量中心性">
              <div ref="eigenvectorCentralityRef" class="chart-container-large"></div>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>

      <!-- 社区检测结果 -->
      <a-col :xs="24" v-if="statistics.communities?.length">
        <a-card title="社区结构" size="small">
          <div class="communities-section">
            <a-row :gutter="[16, 16]">
              <a-col :xs="24" :lg="16">
                <div ref="communityChartRef" class="chart-container-large"></div>
              </a-col>
              <a-col :xs="24" :lg="8">
                <div class="community-list">
                  <div
                    v-for="community in statistics.communities"
                    :key="community.communityId"
                    class="community-item"
                  >
                    <div class="community-header">
                      <a-tag :color="community.color">
                        {{ community.communityName }}
                      </a-tag>
                      <span class="community-size">{{ community.nodeCount }} 个节点</span>
                    </div>
                    <div class="community-modularity">
                      模块度: {{ community.modularity?.toFixed(3) }}
                    </div>
                  </div>
                </div>
              </a-col>
            </a-row>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 网络健康指标 -->
    <a-row :gutter="[16, 16]" class="health-metrics">
      <a-col :xs="24">
        <a-card title="网络健康指标" size="small">
          <a-row :gutter="[16, 16]">
            <a-col :xs="24" :sm="8">
              <div class="health-metric">
                <div class="metric-title">聚类系数</div>
                <a-progress
                  :percent="statistics.clusteringCoefficient * 100"
                  :stroke-color="getHealthColor(statistics.clusteringCoefficient)"
                  :show-info="false"
                />
                <div class="metric-value">
                  {{ (statistics.clusteringCoefficient * 100).toFixed(1) }}%
                </div>
              </div>
            </a-col>
            <a-col :xs="24" :sm="8">
              <div class="health-metric">
                <div class="metric-title">连通性</div>
                <a-progress
                  :percent="getConnectivityPercent()"
                  :stroke-color="getHealthColor(getConnectivityPercent() / 100)"
                  :show-info="false"
                />
                <div class="metric-value">
                  {{ statistics.connectedComponents }} 个连通分量
                </div>
              </div>
            </a-col>
            <a-col :xs="24" :sm="8">
              <div class="health-metric">
                <div class="metric-title">平均路径长度</div>
                <a-progress
                  :percent="getPathLengthPercent()"
                  :stroke-color="getHealthColor(1 - getPathLengthPercent() / 100)"
                  :show-info="false"
                />
                <div class="metric-value">
                  {{ statistics.averagePathLength?.toFixed(2) }}
                </div>
              </div>
            </a-col>
          </a-row>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import {
  ApartmentOutlined,
  ShareAltOutlined,
  NodeIndexOutlined,
  ClusterOutlined
} from '@ant-design/icons-vue'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'

interface NetworkStatistics {
  totalNodes: number
  totalEdges: number
  averageDegree: number
  networkDensity: number
  clusteringCoefficient: number
  connectedComponents: number
  averagePathLength?: number
  networkDiameter?: number
  communities?: CommunityInfo[]
  centralityRankings?: CentralityRanking[]
}

interface CommunityInfo {
  communityId: number
  communityName: string
  nodeCount: number
  nodeIds: string[]
  modularity?: number
  color: string
}

interface CentralityRanking {
  nodeId: string
  nodeName: string
  degreeCentrality: number
  betweennessCentrality: number
  closenessCentrality: number
  eigenvectorCentrality: number
  rank: number
}

interface Props {
  statistics: NetworkStatistics
  nodeData?: any[]
  edgeData?: any[]
}

const props = defineProps<Props>()

// 响应式数据
const centralityTab = ref('degree')

// 图表容器引用
const degreeDistributionRef = ref<HTMLElement>()
const nodeTypeDistributionRef = ref<HTMLElement>()
const relationshipTypeDistributionRef = ref<HTMLElement>()
const strengthDistributionRef = ref<HTMLElement>()
const degreeCentralityRef = ref<HTMLElement>()
const betweennessCentralityRef = ref<HTMLElement>()
const closenessCentralityRef = ref<HTMLElement>()
const eigenvectorCentralityRef = ref<HTMLElement>()
const communityChartRef = ref<HTMLElement>()

// 图表实例
const charts = ref<Record<string, ECharts>>({})

// 初始化所有图表
const initCharts = () => {
  nextTick(() => {
    initDegreeDistributionChart()
    initNodeTypeDistributionChart()
    initRelationshipTypeDistributionChart()
    initStrengthDistributionChart()
    initCentralityCharts()
    if (props.statistics.communities?.length) {
      initCommunityChart()
    }
  })
}

// 度数分布图
const initDegreeDistributionChart = () => {
  if (!degreeDistributionRef.value) return

  const chart = echarts.init(degreeDistributionRef.value)
  charts.value.degreeDistribution = chart

  // 计算度数分布数据
  const degreeData = calculateDegreeDistribution()

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    xAxis: {
      type: 'category',
      data: degreeData.map(d => d.degree),
      name: '度数'
    },
    yAxis: {
      type: 'value',
      name: '节点数量'
    },
    series: [{
      type: 'bar',
      data: degreeData.map(d => d.count),
      itemStyle: {
        color: '#1890ff'
      }
    }]
  }

  chart.setOption(option)
}

// 节点类型分布图
const initNodeTypeDistributionChart = () => {
  if (!nodeTypeDistributionRef.value) return

  const chart = echarts.init(nodeTypeDistributionRef.value)
  charts.value.nodeTypeDistribution = chart

  const typeData = calculateNodeTypeDistribution()

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    series: [{
      name: '节点类型',
      type: 'pie',
      radius: '70%',
      data: typeData,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }

  chart.setOption(option)
}

// 关系类型分布图
const initRelationshipTypeDistributionChart = () => {
  if (!relationshipTypeDistributionRef.value) return

  const chart = echarts.init(relationshipTypeDistributionRef.value)
  charts.value.relationshipTypeDistribution = chart

  const relationshipData = calculateRelationshipTypeDistribution()

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    series: [{
      name: '关系类型',
      type: 'pie',
      radius: ['40%', '70%'],
      data: relationshipData,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }

  chart.setOption(option)
}

// 关系强度分布图
const initStrengthDistributionChart = () => {
  if (!strengthDistributionRef.value) return

  const chart = echarts.init(strengthDistributionRef.value)
  charts.value.strengthDistribution = chart

  const strengthData = calculateStrengthDistribution()

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    xAxis: {
      type: 'category',
      data: strengthData.map(d => d.range),
      name: '强度范围'
    },
    yAxis: {
      type: 'value',
      name: '关系数量'
    },
    series: [{
      type: 'bar',
      data: strengthData.map(d => d.count),
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#52c41a' },
          { offset: 1, color: '#1890ff' }
        ])
      }
    }]
  }

  chart.setOption(option)
}

// 中心性图表
const initCentralityCharts = () => {
  if (!props.statistics.centralityRankings?.length) return

  const rankings = props.statistics.centralityRankings.slice(0, 20) // 取前20名

  // 度中心性
  if (degreeCentralityRef.value) {
    const chart = echarts.init(degreeCentralityRef.value)
    charts.value.degreeCentrality = chart

    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' }
      },
      xAxis: {
        type: 'value'
      },
      yAxis: {
        type: 'category',
        data: rankings.map(r => r.nodeName).reverse(),
        axisLabel: {
          interval: 0,
          rotate: 0
        }
      },
      series: [{
        type: 'bar',
        data: rankings.map(r => r.degreeCentrality).reverse(),
        itemStyle: {
          color: '#1890ff'
        }
      }]
    }

    chart.setOption(option)
  }

  // 介数中心性
  if (betweennessCentralityRef.value) {
    const chart = echarts.init(betweennessCentralityRef.value)
    charts.value.betweennessCentrality = chart

    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' }
      },
      xAxis: {
        type: 'value'
      },
      yAxis: {
        type: 'category',
        data: rankings.map(r => r.nodeName).reverse()
      },
      series: [{
        type: 'bar',
        data: rankings.map(r => r.betweennessCentrality).reverse(),
        itemStyle: {
          color: '#52c41a'
        }
      }]
    }

    chart.setOption(option)
  }

  // 接近中心性
  if (closenessCentralityRef.value) {
    const chart = echarts.init(closenessCentralityRef.value)
    charts.value.closenessCentrality = chart

    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' }
      },
      xAxis: {
        type: 'value'
      },
      yAxis: {
        type: 'category',
        data: rankings.map(r => r.nodeName).reverse()
      },
      series: [{
        type: 'bar',
        data: rankings.map(r => r.closenessCentrality).reverse(),
        itemStyle: {
          color: '#722ed1'
        }
      }]
    }

    chart.setOption(option)
  }

  // 特征向量中心性
  if (eigenvectorCentralityRef.value) {
    const chart = echarts.init(eigenvectorCentralityRef.value)
    charts.value.eigenvectorCentrality = chart

    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' }
      },
      xAxis: {
        type: 'value'
      },
      yAxis: {
        type: 'category',
        data: rankings.map(r => r.nodeName).reverse()
      },
      series: [{
        type: 'bar',
        data: rankings.map(r => r.eigenvectorCentrality).reverse(),
        itemStyle: {
          color: '#fa8c16'
        }
      }]
    }

    chart.setOption(option)
  }
}

// 社区图表
const initCommunityChart = () => {
  if (!communityChartRef.value || !props.statistics.communities?.length) return

  const chart = echarts.init(communityChartRef.value)
  charts.value.community = chart

  const communityData = props.statistics.communities.map(c => ({
    name: c.communityName,
    value: c.nodeCount,
    itemStyle: {
      color: c.color
    }
  }))

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} 个节点 ({d}%)'
    },
    series: [{
      name: '社区',
      type: 'pie',
      radius: '70%',
      data: communityData,
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }

  chart.setOption(option)
}

// 计算度数分布
const calculateDegreeDistribution = () => {
  if (!props.nodeData?.length) {
    return Array.from({ length: 10 }, (_, i) => ({
      degree: i + 1,
      count: Math.floor(Math.random() * 20) + 1
    }))
  }

  const degreeMap = new Map<number, number>()
  props.nodeData.forEach(node => {
    const degree = node.degree || 0
    degreeMap.set(degree, (degreeMap.get(degree) || 0) + 1)
  })

  return Array.from(degreeMap.entries())
    .map(([degree, count]) => ({ degree, count }))
    .sort((a, b) => a.degree - b.degree)
}

// 计算节点类型分布
const calculateNodeTypeDistribution = () => {
  const typeColors = {
    CORPORATE: '#1890ff',
    URBAN: '#52c41a',
    CONCEPTUAL: '#722ed1',
    INDIVIDUAL: '#fa8c16',
    HYBRID: '#eb2f96',
    SYSTEM: '#13c2c2'
  }

  const typeLabels = {
    CORPORATE: '企业',
    URBAN: '城市',
    CONCEPTUAL: '概念',
    INDIVIDUAL: '个人',
    HYBRID: '混合',
    SYSTEM: '系统'
  }

  if (!props.nodeData?.length) {
    return Object.entries(typeColors).map(([type, color]) => ({
      name: typeLabels[type as keyof typeof typeLabels],
      value: Math.floor(Math.random() * 50) + 10,
      itemStyle: { color }
    }))
  }

  const typeMap = new Map<string, number>()
  props.nodeData.forEach(node => {
    const type = node.type || 'UNKNOWN'
    typeMap.set(type, (typeMap.get(type) || 0) + 1)
  })

  return Array.from(typeMap.entries()).map(([type, count]) => ({
    name: typeLabels[type as keyof typeof typeLabels] || type,
    value: count,
    itemStyle: { color: typeColors[type as keyof typeof typeColors] || '#666' }
  }))
}

// 计算关系类型分布
const calculateRelationshipTypeDistribution = () => {
  const typeColors = {
    COLLABORATION: '#52c41a',
    COMPETITION: '#f5222d',
    DEPENDENCY: '#1890ff',
    FUSION: '#722ed1',
    COMMUNICATION: '#fa8c16',
    INHERITANCE: '#13c2c2'
  }

  const typeLabels = {
    COLLABORATION: '协作',
    COMPETITION: '竞争',
    DEPENDENCY: '依赖',
    FUSION: '融合',
    COMMUNICATION: '通信',
    INHERITANCE: '继承'
  }

  if (!props.edgeData?.length) {
    return Object.entries(typeColors).map(([type, color]) => ({
      name: typeLabels[type as keyof typeof typeLabels],
      value: Math.floor(Math.random() * 30) + 5,
      itemStyle: { color }
    }))
  }

  const typeMap = new Map<string, number>()
  props.edgeData.forEach(edge => {
    const type = edge.relationshipType || 'UNKNOWN'
    typeMap.set(type, (typeMap.get(type) || 0) + 1)
  })

  return Array.from(typeMap.entries()).map(([type, count]) => ({
    name: typeLabels[type as keyof typeof typeLabels] || type,
    value: count,
    itemStyle: { color: typeColors[type as keyof typeof typeColors] || '#666' }
  }))
}

// 计算强度分布
const calculateStrengthDistribution = () => {
  const ranges = [
    { range: '0-0.2', min: 0, max: 0.2 },
    { range: '0.2-0.4', min: 0.2, max: 0.4 },
    { range: '0.4-0.6', min: 0.4, max: 0.6 },
    { range: '0.6-0.8', min: 0.6, max: 0.8 },
    { range: '0.8-1.0', min: 0.8, max: 1.0 }
  ]

  if (!props.edgeData?.length) {
    return ranges.map(r => ({
      range: r.range,
      count: Math.floor(Math.random() * 20) + 5
    }))
  }

  const strengthMap = new Map<string, number>()
  props.edgeData.forEach(edge => {
    const strength = edge.strength || 0
    const range = ranges.find(r => strength >= r.min && strength <= r.max)
    if (range) {
      strengthMap.set(range.range, (strengthMap.get(range.range) || 0) + 1)
    }
  })

  return ranges.map(r => ({
    range: r.range,
    count: strengthMap.get(r.range) || 0
  }))
}

// 辅助函数
const getHealthColor = (value: number) => {
  if (value >= 0.8) return '#52c41a'
  if (value >= 0.6) return '#1890ff'
  if (value >= 0.4) return '#fa8c16'
  return '#f5222d'
}

const getConnectivityPercent = () => {
  const components = props.statistics.connectedComponents || 1
  return Math.max(0, (1 - (components - 1) / props.statistics.totalNodes) * 100)
}

const getPathLengthPercent = () => {
  const pathLength = props.statistics.averagePathLength || 0
  const maxExpected = Math.log(props.statistics.totalNodes) / Math.log(2) // 期望的对数增长
  return Math.min(100, (pathLength / maxExpected) * 100)
}

// 响应式调整图表大小
const resizeCharts = () => {
  Object.values(charts.value).forEach(chart => {
    chart.resize()
  })
}

// 监听统计数据变化
watch(() => props.statistics, () => {
  initCharts()
}, { deep: true })

// 监听窗口大小变化
onMounted(() => {
  initCharts()
  window.addEventListener('resize', resizeCharts)
})

onUnmounted(() => {
  window.removeEventListener('resize', resizeCharts)
  Object.values(charts.value).forEach(chart => {
    chart.dispose()
  })
})
</script>

<style scoped>
.network-statistics {
  padding: 0;
}

.stats-cards {
  margin-bottom: 16px;
}

.stats-charts {
  margin-bottom: 16px;
}

.health-metrics {
  margin-bottom: 16px;
}

.chart-container {
  height: 200px;
  width: 100%;
}

.chart-container-large {
  height: 300px;
  width: 100%;
}

.communities-section {
  width: 100%;
}

.community-list {
  max-height: 300px;
  overflow-y: auto;
}

.community-item {
  padding: 8px;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  margin-bottom: 8px;
}

.community-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.community-size {
  font-size: 12px;
  color: #666;
}

.community-modularity {
  font-size: 11px;
  color: #999;
}

.health-metric {
  text-align: center;
}

.metric-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.metric-value {
  font-size: 12px;
  color: #333;
  margin-top: 4px;
}

:deep(.ant-statistic-title) {
  font-size: 12px;
}

:deep(.ant-statistic-content) {
  font-size: 18px;
}

:deep(.ant-card-head-title) {
  font-size: 14px;
}

:deep(.ant-tabs-tab) {
  font-size: 12px;
}
</style>